package se.energimyndigheten.lampguiden.bulbreplacement;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.accessibility.AccessibilityEvent;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.viewpagerindicator.UnderlinePageIndicator;

import org.json.JSONException;

import se.energimyndigheten.lampguiden.R;
import se.energimyndigheten.lampguiden.DashboardActivity;
import se.energimyndigheten.lampguiden.LightSource;
import se.energimyndigheten.lampguiden.SubPageActivity;
import se.energimyndigheten.lampguiden.util.AssetsUtil;

import java.io.IOException;
import java.util.ArrayList;

@SuppressWarnings("deprecation")
public class SocketActivity extends SubPageActivity {

    public static final String KEY_SOCKET = "SOCKET";

//    private static final String TAG = SocketActivity.class.getSimpleName();
    private ArrayList<GalleryItem> list;
    private UnderlinePageIndicator indicator;
    private TextView title;
    private static final String HELP_PATH = HTML_BASEPATH + "Help/sv_Socket.html";

    private ViewPager gallery;
    private LightSource[] lights = null;

    private int offsetInDp;

    private DisplayMetrics displaymetrics;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.socket_gallery);
        initGallery();
    }

    /* XML event handler */
    public void handleAction(View v) {
        switch (v.getId()) {
        case R.id.description:
            int galleryItem = gallery.getCurrentItem();
            if (galleryItem < 11) {
                Intent intent = new Intent(this, PowerActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra(KEY_SOCKET, galleryItem);
                startActivity(intent);
            } else {
                final String[] docs = new String[] { "Halogen_reflektor_GU_5_3", "Halogen_reflektor_GU_10", "Halogen_stift_12V", "Halogen_stift_230V", "Lagenergi", "Lysror"};
               
                Intent intent = new Intent(this, ExplainActivity.class);
                String document = docs[galleryItem-9];
                
                String EXPLAIN_PATH = DashboardActivity.HTML_BASEPATH + "Lamptyper/sv_"+document+".html";
                intent.putExtra(ExplainActivity.EXTRA_HTML_PATH, EXPLAIN_PATH);
                intent.putExtra(ExplainActivity.EXTRA_TITLE, lights[galleryItem].getCaption());
                startActivity(intent);
            }
            break;
        default:
            Toast.makeText(this, "Not yet implemented " + v.getId(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onResume() {
        mSelectedActivity = ACTIVITY_SOCKET;
        super.showHelpActionItem(HELP_PATH);
        super.onResume();
    }

    class GalleryItem {
        public GalleryItem(int image, String info) {
            this.image = image;
            this.info = info;
        }

        int image;
        String info;
    }

    static boolean virgin = true;
    private void initGallery() {
        displaymetrics = getResources().getDisplayMetrics();
        offsetInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 120, displaymetrics);
        gallery = (ViewPager) findViewById(R.id.gallery);
        title = (TextView) findViewById(R.id.description);
        list = new ArrayList<GalleryItem>();

        String json = "";

        try {
            json = AssetsUtil.getFileContents(getAssets(), AssetsUtil.JSON_PATH_LIGHTSOURCE);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            lights = AssetsUtil.getLightSourcesFromJson(json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        
        for (LightSource light : lights) {
            list.add(new GalleryItem(light.getImages()[LightSource.IMAGE_BASE], light.getCaption()));
        }

        final PagerAdapter mAdapter = new GalleryAdapter(this.getSupportFragmentManager());
        gallery.setAdapter(mAdapter);
        // TODO: Further visual tuning?
        gallery.requestFocus();
        gallery.setOffscreenPageLimit(12);
        gallery.setPageMargin(-offsetInDp);
        gallery.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {

                    @SuppressLint("WrongViewCast")
                    @Override
                    public void onGlobalLayout() {
                      // make sure it is not called anymore 
                      gallery.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                      int pos = gallery.getCurrentItem();
                      View child = gallery.getChildAt(pos);
                      if (child !=null) { // Added sanity for odd (resume?) cases
                          ImageView i = (ImageView) child.findViewById(R.id.description);
                          if (i!=null) {
                              Drawable d = i.getDrawable();
//                      Toast.makeText(getApplication(), "Width="+d.getBounds()+" "+gallery.getWidth()+" "+i.getWidth(), Toast.LENGTH_SHORT).show();
                              gallery.setPageMargin(6*(d.getBounds().right - gallery.getWidth())/5);
                          }
                      }
                    }
                  });
        
        title.setText(list.get(0).info);
        indicator = (UnderlinePageIndicator) findViewById(R.id.indicator);
        indicator.setFades(false);
        indicator.setFadeDelay(10000);
        indicator.setFadeLength(10000);
        indicator.setBackgroundColor(Color.DKGRAY);
        indicator.setViewPager(gallery);
        indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                title.setText(list.get(position).info);
                String msg = list.get(position).info;
                msg = getResources().getString(R.string.socket_list_prefix)+msg;
                indicator.setContentDescription(list.get(position).info);
                gallery.setContentDescription(msg);
                gallery.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        gallery.setContentDescription(list.get(0).info+" "+getResources().getString(R.string.socket_list_description));
    }

    public class GalleryAdapter extends PagerAdapter {
        public GalleryAdapter(FragmentManager fm) {
        }

        public int getCount() {
            return list == null ? 0 : list.size();
        }

        @Override
        public Object instantiateItem(View collection, int position) {
            final ImageButton i = new ImageButton(getApplicationContext());
            i.setImageResource(list.get(position).image);
            i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            i.setLayoutParams(new android.view.ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            ((ViewPager) collection).addView(i, 0);
            i.setId(R.id.description); // Fake button click
            i.setBackgroundColor(Color.TRANSPARENT); // Hide selector
            i.setContentDescription(list.get(position).info);
            i.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    handleAction(v);
                }
            });
            return i;
        }

        @Override
        public void destroyItem(View collection, int position, Object view) {
            ((ViewPager) collection).removeView((ImageView) view);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == ((ImageView) object);
        }

        public long getItemId(int position) {
            return position;
        }
    }
}
